<?php
namespace Home\Controller;
use Think\Controller;
class ArticleController extends Controller {
	/**
	 * 文章详情页
	 */
    public function index(){
    	$articleId = I('get.aid');
    	$fieldString = "article_id,article_title,article_time,click,article_content";
    	$this->newVisit($articleId);
        $this->pages($articleId);
    	$articleData = D('Article')->findOneArticle($fieldString,['article_id' => $articleId,'is_display' => 1]);
        $hotArticleList = A('index')->hotArticle();
    	$this->assign('articleData',$articleData);
        $this->assign('hotArticleList',$hotArticleList);
        $this->display('article');
    }

    /**
     * 文章访问次数加一
     * @param  int $id 文章唯一id
     */
    protected function newVisit($id){
    	if (session('?visit')) {
    		$visitArray = session('visit');
    		if (!in_array($id, $visitArray)) {
    			$visitArray[] = $id;
    			session('visit',$visitArray);
    			D('Article')->setNumInc('click',['article_id' => $id],1);
    		}
    	} else {
    		$visitArray = array($id);
    		session('visit',$visitArray);
    		D('Article')->setNumInc('click',['article_id' => $id],1);
    	}
    }

    /**
     * 文章上一篇 下一篇
     */
    protected function pages($id){
        $fieldString = "article_id,article_title";
        //上一篇
        $where = array(
            'is_display' => array('eq',1),
            'article_id' => array('gt',$id),
        );
        $prev_topic = D('Article')->selectPages($fieldString,$where);
        if (empty($prev_topic)) {
            $prev_topic['href'] = 'javascript:void(0)';
            $prev_topic['article_title'] = '没有了';
        } else {
            $prev_topic['href'] = U('Article/index',array('aid'=>$prev_topic['article_id']));
        }
        $this->assign('prev_topic',$prev_topic); 

        //下一篇
        $where = array(
            'is_display' => array('eq',1),
            'article_id' => array('lt',$id),
        );
        $next_topic =  D('Article')->selectPages($fieldString,$where);
        if (empty($next_topic)) {
            $next_topic['href'] = 'javascript:void(0)';
            $next_topic['article_title'] = '没有了';
        } else {
            $next_topic['href'] = U('Article/index',array('aid'=>$next_topic['article_id']));
        }
        $this->assign('next_topic',$next_topic);  
    }

    /**
     * 评论后畅言回推数据设置评论自增
     */
    public function tsetArticleCommenNumInc(){
        $data = I('post.');
        $data = json_decode($data,true);
        $id = $data['sourceid'];
        D('Article')->setNumInc('num_comment',['article_id' => $id],1);
    }
}